"""
pip install pymongo
"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from pymongo import MongoClient
from file.configutil import ConfigUtil
from bson.objectid import ObjectId
import datetime


class DbUtil:

    def __init__(self, db_file):
        cfg = DbConfig(db_file, model_name="mongo")
        self.conn = MongoClient(cfg.host, cfg.port)
        self.db = self.conn[cfg.db_name]  # 指定数据库
        self.db.authenticate(cfg.user, cfg.password)
        self.my_set = self.db["jtk_dialog"]

    def find_one(self, filter=None, *args, **kwargs):
        """
        返回一条map()记录
        :param filter:
        :param args:
        :param kwargs: 查询条件
        :return:
        """
        try:
            re = self.my_set.find_one(filter, *args, **kwargs)
        except TypeError as error:
            print(error)
            re = None
        return re

    def find(self, limit=10, *args, **kwargs):
        """
        返回LIST[map()记录
        :param limit:返回的记录限制条数
        :param args:
        :param kwargs: 查询条件
        :return:
        """
        try:
            re = self.my_set.find(*args, **kwargs).limit(limit)
            re_list = []
            for i in re:
                re_list.append(i)
            print("查询到%d条数据,查询条件%s" % (len(re_list), str(kwargs)))
        except TypeError as error:
            print(error)
            re_list = None
        return re_list

    def insert(self, doc_or_docs, manipulate=True,
               check_keys=True, continue_on_error=False, **kwargs):
        """
        返回<class 'list'>
        [ObjectId('5abb525630ee597e4a04d891')]
        :param doc_or_docs:
        :param manipulate:
        :param check_keys:
        :param continue_on_error:
        :param kwargs:
        :return:
        """
        result = self.my_set.insert(doc_or_docs, manipulate,
               check_keys, continue_on_error, **kwargs)
        print(type(result))
        return result

    def remove(self, *args, **kwargs):
        """
        返回类型
        <class 'dict'>
        {'ok': 1, 'n': 1}
        :param args:
        :param kwargs:
        :return:
        """
        remove_result = self.my_set.remove(*args, **kwargs)
        return remove_result

    def remove_all(self):
        """
        删除表里的所有数据。慎用
        :return:
        """
        self.my_set.remove()

    def update(self,spec, document, upsert=False, manipulate=False,
               multi=False, check_keys=True, **kwargs):
        """
        返回dict: {'nModified': 0, 'ok': 1, 'updatedExisting': True, 'n': 1}
        :param spec:
        :param document:
        :param upsert:
        :param manipulate:
        :param multi:
        :param check_keys:
        :param kwargs:
        :return:
        """
        result = self.my_set.update(spec, document, upsert, manipulate,
               multi, check_keys, **kwargs)
        print(type(result))
        return result


class DbConfig:

    def __init__(self, db_file, model_name):
        config_util = ConfigUtil()
        config_util.read_config(db_file)
        self.__host = config_util.get_opt_value(model_name, "mongo.host")
        self.__port = config_util.get_opt_value(model_name, "mongo.port")
        self.__user = config_util.get_opt_value(model_name, "mongo.user")
        self.__password = config_util.get_opt_value(model_name, "mongo.pwd")
        self.__db_name = config_util.get_opt_value(model_name, "mongo.dbName")

    @property
    def host(self):
        return self.__host

    @property
    def port(self):
        return int(self.__port)

    @property
    def user(self):
        return self.__user

    @property
    def password(self):
        return self.__password

    @property
    def db_name(self):
        return self.__db_name


if __name__ == '__main__':
    file = "db.cfg"
    util = DbUtil(file)
    # result = util.find_one({"customerUserId": "5abb525630ee597e4a04d891"})

    # result = util.find(10, {"_id": ObjectId("5abb525630ee597e4a04d891")})
    # re = util.remove({"_id": ObjectId("5abb525630ee597e4a04d891")})

    msg = [{'_id': ObjectId('5abb525630ee597e4a04d891'), 'finishType': '01',
      'endTime': datetime.datetime(2017, 7, 4, 3, 16, 42, 978000), 'customerUserName': 'jtalk001', 'status': '02',
      'createdDate': datetime.datetime(2017, 7, 4, 2, 50, 9, 27000), 'customerUserId': '110020000000114580',
      'initSource': '03', 'isInvitedComment': False, 'modifiedDate': datetime.datetime(2017, 7, 4, 3, 16, 42, 978000),
      'customerServiceUserId': '110010000000114608', 'isRepeatDialog': False, 'warningType': '00', 'isRated': False,
      'beginTime': datetime.datetime(2017, 7, 4, 2, 50, 9, 25000), 'initType': '01', 'skillGroupId': '5',
      'duration': 1593, 'customerServiceUserName': 'zhuyan52'}]
    #　result = util.insert(msg)
    result = util.update({"_id": ObjectId("5abb525630ee597e4a04d891")}, {"$set": {'customerServiceUserName': 'zhuyan53'}})

    print(result)






